/*********************************************************************************
 *      Copyright:  (C) 2018 Wu Yujun<540726307@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  demo_signal.c
 *    Description:  This file is IPC of signal
 *                 
 *        Version:  1.0.0(2018年12月28日)
 *         Author:  Wu Yujun <540726307@qq.com>
 *      ChangeLog:  1, Release initial version on "2018年12月28日 19时33分12秒"
 *                 
 ********************************************************************************/

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>

int    g_child_stop = 1 ;
int    g_parent_stop = 1 ;
int    g_chil_exit = 0 ;

void signal_worker1(int signum) 
{
    if(signum == SIGUSR1)
    {
        g_parent_stop = 0 ;
    }
    if(signum == SIGUSR2)
    {
        g_child_stop = 0 ;
        g_parent_stop = 1;
    }
    if(signum == SIGCHLD)
    {
        printf("Child process is exit!\n");
        g_chil_exit = 1 ;
    }
}

int main(int argc, char **argv)
{
    int     pid ;
    int     wstatus ;

    signal(SIGUSR1,signal_worker1 ) ;
    signal(SIGUSR2,signal_worker1 ) ;
    signal(SIGCHLD,signal_worker1 ) ;

    pid = fork() ;
    if(pid < 0)
    {
        printf("fork() failed: %s\n", strerror(errno));
        return -1 ;
    }
    if(pid == 0) // child process
    {
        printf("child process is running , pid = %d\n", getpid());
        sleep(2) ;
        /* child process can do somting in here ... */
        printf("Child process do someting over, and send sinal to parent process[%d]\n", getppid());
        kill(getppid() ,SIGUSR1) ;
        while(g_child_stop ) 
        {
            ;
        }
        printf("Child process will exit...\n") ;
        sleep(1) ;
        exit(2) ; 
    }
    /* parent process */
    while( g_parent_stop )
    {
        ;
    }
    printf("Parent process is running, pid = %d\n", getpid()) ;
    /* parent process can do someting in here */
    sleep(3) ;
    printf("Parent process do someting over, and send sinal to Child process[%d]\n", pid);
    kill(pid, SIGUSR2) ;
    wait(&wstatus) ;//parent process will block in here until child process exit
    if( g_chil_exit )
    {
        printf("Parent receive child exit signal\n");    
    }


    return 0 ;
}
